import { useRequest } from 'ahooks'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { getUserService } from '../services/user'
import { loginReducer } from '../store/userReducer'
import userGetUserInfo from './useGetUserInfo'

export default function userLoadUserData() {
  const [waitingUserData, setWaitingUserData] = useState(true)
  const dispatch = useDispatch()
  const { username } = userGetUserInfo()

  // ajax 加载用户信息
  const { run } = useRequest(async () => await getUserService(), {
    manual: true,
    onSuccess({ username, nickname }) {
      dispatch(loginReducer({ username, nickname }))
    },
    onFinally() {
      setWaitingUserData(false)
    },
  })

  // 判断当前 redux store 是否已经存在用户信息
  useEffect(() => {
    if (username) {
      setWaitingUserData(false)
      return
    }

    run() // 如果 redux store  中没有用户信息,则进行加载
  }, [username])
  // ajax加载完用户数据后, 放在 redux 中, 不用返回

  return { waitingUserData }
}
